<template>
  <div>
    <div class="header">
      <span class="iconfont iconjiantou2" @click="goBack"></span>
      <div class="search">
        <span class="iconfont iconsearch"></span>
        <input type="text" v-model="keyword" />
      </div>
      <div class="btn" @click="search">搜索</div>
    </div>

    <div class="suggestions" v-if="results.length === 0">
      <h2 class="title">历史记录</h2>
      <div class="history list">
        <div class="item" @click="sendSuggestion(item)" v-for="(item, index) in history" :key="index">{{ item }}</div>
      </div>
      <h2 class="title">热门搜索</h2>
      <div class="history list">
        <div class="item" @click="sendSuggestion(item)" v-for="(item, index) in hot" :key="index">{{ item }}</div>
      </div>
    </div>
    <PostItem :postData="item" v-for="item in results" :key="item.id" />
  </div>
</template>

<script>
import PostItem from '../components/PostItem'
export default {
  components: {
    PostItem
  },
  data() {
    return {
      keyword: '',
      results: [],
      history: [],
      hot: ['美女', '阿信']
    }
  },
  created() {
    const historyStorage = localStorage.getItem('history')
    if (historyStorage) {
      this.history = JSON.parse(historyStorage)
    }
  },
  watch: {
    keyword(newVal) {
      if (!newVal) {
        this.results = []
      }
    },
    history() {
      localStorage.setItem('history', JSON.stringify(this.history))
    }
  },
  methods: {
    search() {
      this.$axios({
        url: '/post_search',
        params: {
          keyword: this.keyword
        }
      }).then(res => {
        console.log(res.data)

        if (this.history.indexOf(this.keyword) === -1) {
          this.history.push(this.keyword)
        }

        this.results = res.data.data
      })
    },
    sendSuggestion(item) {
      this.keyword = item
      this.search()
    },
    goBack() {
      if (this.results.length === 0) {
        this.$router.back()
      } else {
        this.keyword = ''
      }
    }
  }
}
</script>

<style lang="less" scoped>
.header {
  padding: 2.7778vw;
  display: flex;
  align-items: center;
  .search {
    position: relative;
    .iconsearch {
      position: absolute;
      top: 50%;
      left: 10%;
      transform: translate(-50%, -50%);
    }
    input {
      flex: 1;
      width: 71.6667vw;
      height: 10.5556vw;
      margin: 0 2.7778vw;
      border-radius: 4.7222vw;
      border: 1px solid #888;
      text-indent: 2em;
      font-size: 4.4444vw;
    }
  }
  .btn {
    font-size: 3.8889vw;
  }
}
.suggestions {
  padding: 2.7778vw;
  .title {
    font-size: 3.8889vw;
    margin-top: 5.5556vw;
  }
  .list {
    display: flex;
    .item {
      padding: 2.7778vw;

      font-size: 3.3333vw;
    }
  }
}
</style>
